package com.winner.data.util;

import java.io.FileInputStream;
import java.util.Map;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;

import javax.xml.xpath.XPathConstants;

/**
 * hutool封装一个通用的xml解析的工具类, 把xml中某个xpath路径的内容解析为java对象
 *
 * @author wangxinle5
 * @since 2024-05-22
 */
public class HutoolXmlParser {
// <?xml version='1.0' encoding='UTF-8'?>
//<root>
//    <content>
//        <user>
//            <data>111</data>
//            <data1>aa</data1>
//        </user>
//        <user>
//            <data>222</data>
//            <data1>bb</data1>
//        </user>
//    </content>
//</root>

    public static void main(String[] args) throws Exception {
        //  解析XML字符串拿到某个标签的值
        String xmlStr = "<?xml version='1.0' encoding='UTF-8'?><MSG><Head><MessageSubType>123</MessageSubType></Head></MSG>";
        Document document = XmlUtil.parseXml(xmlStr);

        Object bString = XmlUtil.getByXPath("/MSG/Head/MessageSubType", document, XPathConstants.STRING);
        System.out.println(bString);

        // 读取XML文件内容为字符串
        String xml = IoUtil.read(new FileInputStream("D:/1.xml"), "UTF-8");
        Map<String, Object> stringObjectMap = XmlUtil.xmlToMap(xml);
        System.out.println(findByKeyInMap(stringObjectMap,"user"));


    }

    // 假设我们有一个递归方法来查找特定键
    public static Object findByKeyInMap(Map<String, Object> map, String key) {
        if (map.containsKey(key)) {
            return map.get(key);
        }
        // 遍历值，检查是否包含嵌套的Map
        for (Object value : map.values()) {
            if (value instanceof Map) {
                Object foundValue = findByKeyInMap((Map<String, Object>) value, key);
                if (foundValue != null) {
                    return foundValue;
                }
            }
        }

        return null;
    }

}

